package com.xintoucloud.pbs.controller;

import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.xintoucloud.pbs.entity.PartyMember;
import com.xintoucloud.pbs.model.Node;
import com.xintoucloud.pbs.service.MenuService;
import com.xintoucloud.pbs.service.PartyMemberService;


@Controller@RequestMapping("/all")
public class LoginController {
	
	@Autowired
	private PartyMemberService partyMemberService;
	@Autowired
	private MenuService menuService;
	@RequestMapping("/loginOut")
	public String loginOut(HttpSession session,HttpServletRequest request,HttpServletResponse response) {
		//删除自动登录的Cookie
		Cookie[] cookies = request.getCookies();
		if(cookies != null){
			for(Cookie c : cookies){
				String name = c.getName();
				System.out.println("loginoutName"+name);
				if(name.equals("logindPid")||name.equals("JSESSIONID")){
					c.setMaxAge(0);
					//重写发送
					response.addCookie(c);
					break;
				}
			}
		}
		session.invalidate();
		return "redirect:toLoginPage";
	}
	@RequestMapping("/toLoginPage")
	public String toLoginPage(HttpSession session,Model m) {
		String Message=(String) session.getAttribute("LoginFail");
		System.out.println("Message:"+Message);
		m.addAttribute("msg", Message);
		session.invalidate();
		return "login";
	}
	@RequestMapping("/toHome")
	public String toHome(HttpSession session,Model m) {
		PartyMember partyMember=(PartyMember) session.getAttribute("loginPartyMember");
		List <Node> nodes=menuService.listNodeByParentId(0,partyMember.getPmp().getPpid());
		m.addAttribute("nodes", nodes);
		return "home";
	}

	@PostMapping("/login")
	public String Login(String pname,String ppswd,HttpSession session,Model m,HttpServletRequest request,HttpServletResponse response) {
		System.out.println("pname:"+pname+",ppswd"+ppswd);
		if(!pname.trim().equals("")&&!ppswd.trim().equals("")&&pname!=null&&ppswd!=null) {
			PartyMember partyMember = partyMemberService.login(pname, ppswd);
			if(partyMember!=null) {
				List <Node> nodes=menuService.listNodeByParentId(0,partyMember.getPmp().getPpid());
				m.addAttribute("nodes", nodes);
				session.setAttribute("loginPartyMember", partyMember);
				return "redirect:/all/toHome";
			}else {
				System.out.println("lidong");
				session.setAttribute("LoginFail", "登录失败!请检查账号密码是否输入正确");
				return "redirect:/all/toLoginPage";
			}
		}
		session.setAttribute("LoginFail","账号密码不能为空，请重新输入");
		return "redirect:/all/toLoginPage";	
	}
}
